<?php

class EMailController extends Controller
{
    public $layout = '//layouts/column1';

    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
            'checkMailActivation', // 判断用户是否验证(激活)了邮箱.
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('update', 'exists'),
                'users' => array('*'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     */
    public function actionUpdate()
    {
        if (isset($_POST['email'])) {

            $email = $_POST['email'];
            $newEmail = $_POST['new_email'];
            $password = md5($_POST['password']);

            // 新旧密码相同的情况下,如果验证邮箱和密码匹配成功的话,那么就执行更新
            if ($email != $newEmail) {
                $model = User::model()->findByAttributes(array('email' => $email, 'password' => $password));

                if ($model != null) {
                    $model->email = $newEmail;

                    // 更新新邮箱
                    if ($model->save()) {
                        // TODO: 发送确认邮件到新邮箱

                        // 更新session中的邮箱地址
                        Yii::app()->session['email'] = $newEmail;

                        // 设置'更改成功'提示信息
                        Yii::app()->user->setFlash('success', '<strong>更新成功:</strong>请到刚刚修改的新邮箱 <span id="lblEmail">' . $newEmail . '</span> 中<a href="#" id="lnkMailBox">查收邮件</a>,并点击邮件里面的链接进行邮箱验证!');
                    } else {
                        Yii::app()->user->setFlash('error', '<strong>错误提示:</strong>哇喔,出现了些未知问题,请重试!');
                    }

                } else {
                    Yii::app()->user->setFlash('error', '<strong>重要提示:</strong>您填写的邮箱和密码经验证不匹配,请重新填写!');
                }

            } else {
                Yii::app()->user->setFlash('warning', '<strong>错误提示:</strong>打酱油呢?你想要设置的新邮箱和当前邮箱是相同的!');
            }
        }

        $this->render('../user/update-email');
    }

    public function actionExists()
    {
        isset($_POST['email']) && $model = User::model()->findByAttributes(array('email' => $_POST['email']));

        // NOTE: true返回到客户端将会是"1",false返回到客户端将上面都没有
        echo isset($model) && $model !== null;
        exit;
    }

    public function filterCheckMailActivation($filterChain){
        Yii::app()->user->setFlash('email-activation', '<strong>重要提示 : </strong>您的注册邮箱还没有通过验证,请立即验证,否则你在本站使用的功能将受限!');
        $filterChain->run();
    }
}
?>